package com.guigu.equipmentservice.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.R;
import com.guigu.equipmentservice.entity.*;
import com.guigu.equipmentservice.mapper.DetectionReportMapper;
import com.guigu.equipmentservice.mapper.EquipmentMapper;
import com.guigu.equipmentservice.service.EquipmentImageService;
import com.guigu.equipmentservice.service.EquipmentService;
import com.guigu.equipmentservice.service.EquipmentVideoService;
import com.guigu.equipmentservice.vo.BusinessmanEquipmentVo;
import com.guigu.equipmentservice.vo.EquipmentVo;
import com.guigu.equipmentservice.vo.EquipmentVo;
import com.guigu.userservice.entity.User;
import com.guigu.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import com.guigu.equipmentservice.service.EquipmentTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

import java.util.List;

/**
 * <p>
 * 设备表（存储卖家发布的二手机械信息） 服务实现类
 * </p>
 *
 * @author zcy
 * @since 2025-09-28
 */
@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment> implements EquipmentService {

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private DetectionReportMapper detectionReportMapper;

    @Autowired
    private EquipmentTypeService equipmentTypeService;

    @Autowired
    private EquipmentImageService equipmentImageService;

    @Autowired
    private EquipmentVideoService equipmentVideoService;


    /**
     * 前台-查询前14个设备品牌
     * */
    @Override
    public List<Equipment> selectfrontshisiEquipmentBrand() {

        List<Equipment> equipment = equipmentMapper.selectfrontshisiEquipmentBrand();

        return equipment;
    }

    @Override
    public R selectEquipmentByType(EquipmentVo vo, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<Equipment> equipment = equipmentMapper.selectEquipmentByType(vo);
        for (Equipment e:equipment) {
            QueryWrapper<EquipmentImage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("equipment_id",e.getEquipmentId());
            List<EquipmentImage> equipmentImages=equipmentImageService.list(queryWrapper);
            if (!equipmentImages.isEmpty()) {
                e.setEquipmentImages(equipmentImages);
            }
        }
        PageInfo<Equipment> pageInfo= new PageInfo<>(equipment);
        return R.ok().data("pageInfo",pageInfo);
    }

    @Override
    public R selectEquipmentById(Long id) {
        Equipment equipment = equipmentMapper.selectEquipmentById(id);
        return R.ok().data("equipment",equipment);
    }

    @Override
    public R updateEquipmentStatus(Long id, Integer status) {
        Equipment equipment = new Equipment();
        equipment.setEquipmentId(id);
        equipment.setStatus(status);
        this.updateById(equipment);
        return R.ok();
    }

    @Override
    public List<Equipment> selectAllEquipmentInfo() {
        List<Equipment> equipment = equipmentMapper.selectAllEquipmentInfo();
        return equipment;
    }

    @Override
    public List<Equipment> selectEquipmentByBusinVo(Integer Bid,BusinessmanEquipmentVo vo) {
        //根据业务员ID拿到业务员与设备检测关联表
        LambdaQueryWrapper<DetectionReport> detectionReportLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detectionReportLambdaQueryWrapper.eq(DetectionReport::getBusinessmanId,Bid);
        //筛选：检测报告审核状态（searchReportAuditStatus）
        if (vo.getSearchReportAuditStatus() != null){
            if (vo.getSearchReportAuditStatus() == 0){
                detectionReportLambdaQueryWrapper.eq(DetectionReport::getAuditStatus,vo.getSearchReportAuditStatus());
            }else{
                //查询数据库不等于0的
                detectionReportLambdaQueryWrapper.ne(DetectionReport::getAuditStatus,0);
            }

        }
        //拿到所有与传过来的业务员相关联的设备
        List<DetectionReport> detectionReports = detectionReportMapper.selectList(detectionReportLambdaQueryWrapper);
        //新建一个集合方便后续返回
        List<Equipment> equipmentArrayList = new ArrayList<>();
        //循环遍历equipmentArrayList
        for (DetectionReport Dete:detectionReports) {
            LambdaQueryWrapper<Equipment> wrapper = new LambdaQueryWrapper<>();
            //根据设备ID查询设备，比加
            wrapper.eq(Equipment::getEquipmentId,Dete.getEquipmentId());
            //筛选：设备是否被检测（searchIsDetected）
            if (vo.getSearchIsDetected()!=  null){
                wrapper.eq(Equipment::getIsDetected,vo.getSearchIsDetected());
            }
            //筛选：设备名称（searchEquipmentName）
            if (vo.getSearchEquipmentName() != null){
                wrapper.like(Equipment::getBrand,vo.getSearchEquipmentName());
            }
            //设备类型
            if (vo.getEquipmentType() != null){
                wrapper.eq(Equipment::getTypeId,vo.getEquipmentType());
            }
            //查询出设备
            Equipment equipment = equipmentMapper.selectOne(wrapper);
            //存入集合中
            equipmentArrayList.add(equipment);
        }
        //返回集合
        return equipmentArrayList;
    }

    @Override
    public Equipment selectEquipmentByIdFeign(Long id) {
        Equipment equipment = equipmentMapper.selectEquipmentById(id);
        return equipment;
    }

    @Override
    public List<Equipment> selectAllEquipment() {
        List<Equipment> equipment = equipmentMapper.selectList( null);
        return equipment;
    }

    @Override
    public PageInfo<Equipment> pageEquipmentByVo(Integer pageNum, Integer pageSize, EquipmentVo equipmentVo) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
        //上架状态
        if (equipmentVo.getStatus() != null || equipmentVo.getStatus() != "")
            queryWrapper.eq("status",equipmentVo.getStatus());
        // 设备类型
        if (equipmentVo.getType() != null && !equipmentVo.getType().isEmpty())
            queryWrapper.eq("type_id", equipmentVo.getType());

        // 设备品牌
        if (equipmentVo.getBrand() != null && !equipmentVo.getBrand().isEmpty())
            queryWrapper.eq("brand", equipmentVo.getBrand());

        // 设备所在地
        if (equipmentVo.getLocation() != null && !equipmentVo.getLocation().isEmpty())
            queryWrapper.eq("location", equipmentVo.getLocation());

        List<Equipment> equipment = equipmentMapper.selectList(queryWrapper);
        PageInfo<Equipment> pageInfo = new PageInfo<>(equipment);
        return pageInfo;
    }




    private List<Long> getAllChildTypeIds(Long parentId) {
        List<Long> typeIds = new ArrayList<>();
        typeIds.add(parentId);
        QueryWrapper<EquipmentType> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<EquipmentType> childTypes = equipmentTypeService.list(wrapper);
        for (EquipmentType child : childTypes) {
            typeIds.addAll(getAllChildTypeIds(child.getTypeId()));
        }
        return typeIds;
    }


    @Override
    public PageInfo<Equipment> queryEquipmentPage(Integer pageNum, Integer pageSize,  EquipmentVo equipmentVo) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);

        //设备类型筛选
        Long selectedTypeId = equipmentVo.getSelectedTypeId();
        if (selectedTypeId != null && selectedTypeId > 0) {
            List<Long> allTypeIds = getAllChildTypeIds(selectedTypeId);
            if (!allTypeIds.isEmpty()) {
                wrapper.in("type_id", allTypeIds);
            }
        }
        //设备型号筛选
        if (equipmentVo.getModel() != null && !equipmentVo.getModel().isEmpty()){
            wrapper.in("model",equipmentVo.getModel());
        }
        //设备品牌筛选
        if (!StringUtils.isEmpty(equipmentVo.getBrand())){
            wrapper.eq("brand",equipmentVo.getBrand());
        }

        //价格筛选
        if (equipmentVo.getMinPrice()!=null) {
            wrapper.ge("price", equipmentVo.getMinPrice());
        }
        if (equipmentVo.getMaxPrice()!=null) {
            wrapper.le("price", equipmentVo.getMaxPrice());
        }
        //省份筛选
        if (!StringUtils.isEmpty(equipmentVo.getLocation())){
            wrapper.like("location", equipmentVo.getLocation()+"%");
        }

        //时间筛选
        List<String> timeRanges = equipmentVo.getTimeRange();
        if (timeRanges != null && !timeRanges.isEmpty()) {
            LocalDateTime endTime = LocalDateTime.now();
            wrapper.and(w -> {
                for (String timeRangeValue : timeRanges) {
                    LocalDateTime startTime = null;
                    boolean isOverThreeMonths = false;
                    switch (timeRangeValue) {
                        case EquipmentVo.TimeRange.ONE_DAY:
                            startTime = endTime.minusDays(1);
                            break;
                        case EquipmentVo.TimeRange.THREE_DAYS:
                            startTime = endTime.minusDays(3);
                            break;
                        case EquipmentVo.TimeRange.ONE_WEEK:
                            startTime = endTime.minusWeeks(1);
                            break;
                        case EquipmentVo.TimeRange.ONE_MONTH:
                            startTime = endTime.minusMonths(1);
                            break;
                        case EquipmentVo.TimeRange.THREE_MONTHS:
                            startTime = endTime.minusMonths(3);
                             break;
                        case EquipmentVo.TimeRange.MORE_THAN_THREE_MONTHS:
                            startTime = endTime.minusMonths(3);
                                isOverThreeMonths = true;
                            break;
                        default:
                            continue;
                    }
                   if (startTime!=null){
                       if (isOverThreeMonths){
                           w.or().le("release_time", startTime);
                       }else {
                           w.or().ge("release_time", startTime);
                       }
                   }

                }
            });
        }

        //排序
        if (!StringUtils.isEmpty(equipmentVo.getSortType())){
            switch (equipmentVo.getSortType()){
                case EquipmentVo.SortType.PRICE_ASC:
                    wrapper.orderByAsc("price");
                    break;
                case EquipmentVo.SortType.PRICE_DESC:
                    wrapper.orderByDesc("price");
                    break;
                case EquipmentVo.SortType.TIME_DESC:
                    wrapper.orderByDesc("release_time");
                    break;
                case EquipmentVo.SortType.TIME_ASC:
                    wrapper.orderByAsc("release_time");
                    break;
                case EquipmentVo.SortType.HOUR_ASC:
                        wrapper.orderByAsc("hour");
                        break;
                case EquipmentVo.SortType.HOUR_DESC:
                    wrapper.orderByDesc("hour");
                    break;
                case EquipmentVo.SortType.YEAR_ASC:
                        wrapper.orderByAsc("year");
                        break;
                case EquipmentVo.SortType.YEAR_DESC:
                        wrapper.orderByDesc("year");
                        break;
                default:
                    wrapper.orderByDesc("create_time");
                    break;
            }
        }else {
            wrapper.orderByDesc("create_time");

        }
        List<Equipment> equipment = equipmentService.list(wrapper);

        for (int i=0;i<equipment.size();i++){
            Equipment equipments = equipment.get(i);

            // 根据设备typeId查类型名称
            EquipmentType equipmentType = equipmentTypeService.getById(equipments.getTypeId());
            equipments.setTypeName(equipmentType.getTypeName());

            //根据设备id查询设备图片
            QueryWrapper<EquipmentImage> imageQueryWrapper = new QueryWrapper<>();
            imageQueryWrapper.eq("equipment_id",equipments.getEquipmentId());
            List<EquipmentImage> list1 = equipmentImageService.list(imageQueryWrapper);
            if (!list1.isEmpty()) {
                // 获取第一个设备图片
                EquipmentImage firstImage = list1.get(0);
                equipments.setImageUrl(firstImage.getImageUrl());
            }

            //根据设备id查询设备视频
            QueryWrapper<EquipmentVideo> equipmentVideoQueryWrapper = new QueryWrapper<>();
            equipmentVideoQueryWrapper.eq("equipment_id",equipments.getEquipmentId());
            List<EquipmentVideo> equipmentVideoList = equipmentVideoService.list(equipmentVideoQueryWrapper);
            if (!equipmentVideoList.isEmpty()) {
                // 获取第一个设备视频
                EquipmentVideo equipmentVideo = equipmentVideoList.get(0);
                equipments.setVideoUrl(equipmentVideo.getVideoUrl());
            }
        }
        PageInfo<Equipment> equipmentPageInfo = new PageInfo<>(equipment);
        return equipmentPageInfo;
    }

}
